//
// Created by Luhang on 2023/5/25/025.
//

#ifndef INC_0504_RBTREE_H
#define INC_0504_RBTREE_H

#endif //INC_0504_RBTREE_H

#include <iostream>
#include <ctime>
using namespace std;

enum Colour{
    RED,
    BLACK,
};

template<class K, class V>
struct RBTreeNode{
    RBTreeNode<K, V>* _left;
    RBTreeNode<K, V>* _right;
    RBTreeNode<K, V>* _parent;
    pair<K, V> _kv;
    Colour _col;

    RBTreeNode(const pair<K, V>& kv)
    :_left(nullptr)
    ,_right(nullptr)
    ,_parent(nullptr)
    ,_kv(kv)
    ,_col(RED)//新增红(可能违反规则3，但新增黑一定违反规则4)
    {}
};

template<class K, class V>
class RBTree{
    typedef RBTreeNode<K, V> Node;
public:
    ~RBTree(){
        _Destroy(_root);
        _root = nullptr;
    }

    Node* Find(const K& key){
        Node* cur = _root;
        while (cur){
            if (cur->_kv.first < key)
                cur = cur->_right;
            else if (cur->_kv.first > key)
                cur = cur->_left;
            else
                return cur;
        }
        return nullptr;
    }

    bool Insert(const pair<K, V> kv){
        if (_root == nullptr){
            _root = new Node(kv);
            _root->_col = BLACK;
            return true;
        }

        Node* parent = nullptr;
        Node* cur = _root;
        while (cur){
            if (cur->_kv.first < kv.first){
                parent = cur;
                cur = cur->_right;
            }
            else if (cur->_kv.first > kv.first){
                parent = cur;
                cur = cur->_left;
            } else
                return false;
        }

        //链接
        cur = new Node(kv);
        if (parent->_kv.first > kv.first)
            parent->_left = cur;
        else
            parent->_right = cur;
        cur->_parent = parent;

        //开始修正
        while (parent && parent->_col == RED){
            Node* grandfather = parent->_parent;
            //p在g的左
            if (grandfather->_left == parent){
                Node* uncle = grandfather->_right;
                //情况1：u存在且为红(变色处理，并继续往上处理)
                if (uncle && uncle->_col == RED){
                    parent->_col = BLACK;
                    uncle->_col = BLACK;
                    grandfather->_col = RED;

                    //继续向上调整
                    cur = grandfather;
                    parent = cur->_parent;
                }
                //情况2：u不存在/u存在且为黑(旋转+变色)
                else{
                    //斜线:单旋
                    //    g
                    //  p   u
                    //c
                    if (cur == parent->_left){
                        RotateR(grandfather);
                        parent->_col = BLACK;
                        grandfather->_col = RED;
                    }
                    //折线:双旋
                    //    g
                    //  p   u
                    //    c
                    else{
                        RotateL(parent);
                        RotateR(grandfather);
                        cur->_col = BLACK;
                        grandfather->_col = RED;
                    }
                    //旋转后的根均为黑色，可以跳出
                    break;
                }
            }
            //p在g的右
            //grandfather->_right == parent;
            else{
                Node* uncle = grandfather->_left;
                //情况1：u存在且为红(变色处理，并继续往上处理)
                if (uncle && uncle->_col == RED){
                    parent->_col = BLACK;
                    uncle->_col = BLACK;
                    grandfather->_col = RED;

                    //继续向上调整
                    cur = grandfather;
                    parent = cur->_parent;
                }
                    //情况2：u不存在/u存在且为黑(旋转+变色)
                else{
                    //斜线:单旋
                    //    g
                    //  u   p
                    //        c
                    if (cur == parent->_right){
                        RotateL(grandfather);
                        parent->_col = BLACK;
                        grandfather->_col = RED;
                    }
                        //折线:双旋
                        //    g
                        //  u   p
                        //    c
                    else{
                        RotateR(parent);
                        RotateL(grandfather);
                        cur->_col = BLACK;
                        grandfather->_col = RED;
                    }
                    //旋转后的根均为黑色，可以跳出
                    break;
                }
            }
        }

        _root->_col = BLACK;
        return true;
    }

    void InOrder(){
        _InOrder(_root);
        cout << endl;
    }

    bool IsBalance(){
        //检查根节点颜色
        if (_root && _root->_col == RED){
            cout << "The node's colour of root is red" << endl;
            return false;
        }

        //计算路径上黑色节点个数的基准值
        int benchMark = 0;
        Node* cur = _root;
        while (cur){
            if (cur->_col == BLACK)
                ++benchMark;
            cur = cur->_left;
        }

        //判断红色节点是否连续和黑色节点数量是否相等
        return _Check(_root,0,benchMark);
    }

    int Height(){
        return _Height(_root);
    }

private:
    void RotateL(Node* parent){
        Node* subR = parent->_right;
        Node* subRL = subR->_left;

        parent->_right = subRL;
        if (subRL)
            subRL->_parent = parent;

        Node* pParent = parent->_parent;

        subR->_left = parent;
        parent->_parent = subR;

        if (pParent == nullptr){
            _root = subR;
            subR->_parent = nullptr;
        } else{
            if (pParent->_right == parent)
                pParent->_right = subR;
            else
                pParent->_left = subR;

            subR->_parent = pParent;
        }
    }

    void RotateR(Node* parent){
        Node* subL = parent->_left;
        Node* subLR = subL->_right;

        parent->_left = subLR;
        if (subLR)
            subLR->_parent = parent;

        Node* pParent = parent->_parent;

        subL->_right = parent;
        parent->_parent = subL;

        if (parent == _root){
            _root = subL;
            subL->_parent = nullptr;
        } else{
            if (pParent->_right == parent)
                pParent->_right = subL;
            else
                pParent->_left = subL;
            subL->_parent = pParent;
        }
    }

    void _InOrder(Node* root){
        if (root == nullptr)
            return;
        _InOrder(root->_left);
        cout << root->_kv.first << " ";
        _InOrder(root->_right);
    }

    void _Destroy(Node* root){
        if (root == nullptr)
            return;
        _Destroy(root->_left);
        _Destroy(root->_right);
        delete root;
    }

    int _Height(Node* root){
        if (root == nullptr)
            return 0;
        int leftHeight = _Height(root->_left);
        int rightHeight = _Height(root->_right);

        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    bool _Check(Node* root, int blackNum, int benchMark){
        if (root == nullptr){
            if (blackNum != benchMark){
                cout << "There exist unequal numbers of black nodes" << endl;
                return false;
            }

            return true;
        }

        if (root->_col == BLACK)
            ++blackNum;

        if (root->_col == RED && root->_parent->_col == RED){
            cout << "There exist continuous red node" << endl;
            return false;
        }

        return _Check(root->_left, blackNum, benchMark) && _Check(root->_right, blackNum, benchMark);
    }

    Node* _root = nullptr;
};

void Test_RBTree1(){
    //int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
    int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 16, 3, 7, 11, 9, 26, 18, 14, 15 };
    RBTree<int, int> t1;
    for (auto e : a)
    {
        t1.Insert(make_pair(e, e));
        cout << e << " Insert: " << t1.IsBalance() << endl;
    }

    t1.InOrder();
    cout << t1.IsBalance() << endl;
}

void Test_RBTree2()
{
    srand(time(0));
    const size_t N = 5000000;
    RBTree<int, int> t;
    for (size_t i = 0; i < N; ++i)
    {
        size_t x = rand()+i;
        t.Insert(make_pair(x, x));
        //cout << t.IsBalance() << endl;
    }

    //t.InOrder();

    cout << t.IsBalance() << endl;
    cout << t.Height() << endl;
}